import os
import io
from django import forms
from django.core.files.base import ContentFile
from PIL import Image
from .models import Ouser

def resize_image(file, username, max_size=(80, 80)):
    img = Image.open(file)
    img.thumbnail(max_size, Image.Resampling.LANCZOS)
    output = io.BytesIO()
    img.save(output, format=img.format)
    output.seek(0)
    return ContentFile(output.read(), name=f"{username}{os.path.splitext(file.name)[1]}")

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Ouser
        fields = ['avatar', 'nickname', 'bio']

        widgets = {
            'nickname': forms.TextInput(attrs={'class': 'form-control'}),
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'avatar': forms.FileInput(attrs={'class': 'form-control d-none'}),
        }


    def clean_avatar(self):
        avatar = self.cleaned_data.get('avatar')
        if 'avatar' not in self.changed_data:
            return avatar

        valid_formats = ['image/jpeg', 'image/png', 'image/jpg']
        if avatar.content_type not in valid_formats:
            raise forms.ValidationError("不支持的图片格式，仅支持 jpeg, png, jpg")
        
        return resize_image(avatar, self.instance.username)

    def clean_nickname(self):
        nickname = self.cleaned_data.get('nickname')
        if len(nickname) < 2:
            raise forms.ValidationError("昵称至少需要两个字符。")
        return nickname

    def save(self, commit=True):
        instance = super().save(commit=False)
        if 'avatar' in self.changed_data and self.initial['avatar'].name != 'avatar/default.png':
            self.initial['avatar'].delete()
            instance.avatar = self.cleaned_data.get('avatar')

        if commit:
            instance.save()
        return instance
